package com.wholesale;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.wholesale.beans.GoodsInfo;
import com.wholesale.commons.PageControlView;
import com.wholesale.datas.WebServiceClient;
import com.wholesale.utils.AsyncImageLoader;
import com.wholesale.utils.Constants;

public class WholeSaleLayout extends LinearLayout implements OnClickListener,
		OnItemSelectedListener, OnItemClickListener {
	private ViewFlipper viewFlipper;
	private Context context;
	private View baseView;
	public Button rightButton;
	private RelativeLayout loadingLayout;
	private ArrayList<GoodsInfo> newGoodsInfo = new ArrayList<GoodsInfo>();
	private List<Bitmap> bitmaps;
	private Gallery gallery;
	private ImageView logo;
	private GalleryAdapter ga = null;
	private boolean loadFinished = false;
	private PageControlView pageControl;

	// 用于进行首页数据轮播
	private Timer rotateTimer;
	// 是否已经手动调整过了
	private boolean isManualRotated = false;
	private boolean isAutoRatated = false;
	private Object autoRotatedLock = new Object();

	class RotateTask extends TimerTask {
		@Override
		public void run() {
			if (newGoodsInfo.size() > 0 && !isManualRotated) {
				int size = newGoodsInfo.size();
				int currentIndex = gallery.getSelectedItemPosition();
				int now = (currentIndex + 1) % size;
				Message msg = new Message();
				msg.what = 1002;
				msg.arg1 = now;
				handler.sendMessage(msg);
			}
			isManualRotated = false;
		}
	}

	// 构造函数
	public WholeSaleLayout(Context context, final ViewFlipper viewFlipper) {
		super(context);
		this.viewFlipper = viewFlipper;
		this.context = context;
		// 加载需要的属性，加载方法一的子Layout
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(
				R.layout.wholesale, this);
		logo = (ImageView) baseView.findViewById(R.id.imageView1);
		gallery = (Gallery) baseView.findViewById(R.id.myGallery);
		rightButton = (Button) baseView.findViewById(R.id.rightBtn);
		rightButton.setBackgroundResource(R.drawable.affiche_user_off);
		rightButton.setOnClickListener(this);
		if (Constants.userInfo == null) {
			rightButton.setBackgroundResource(R.drawable.affiche_user_off);
		} else {
			rightButton.setBackgroundResource(R.drawable.affiche_user_on);
		}
		loadingLayout = (RelativeLayout) baseView
				.findViewById(R.id.loadingLayout);
		ga = new GalleryAdapter(context);
		gallery.setAdapter(ga);
		gallery.setOnItemSelectedListener(this);
		gallery.setOnItemClickListener(this);

		pageControl = (PageControlView) baseView
				.findViewById(R.id.pageControlNew);

		// 异步调用webservice获取首页商品
		GoodsListAsync goodsListAsync = new GoodsListAsync(context);
		goodsListAsync.execute((Void) null);
	}

	public void login(boolean isLogin) {
		if (isLogin) {
			rightButton.setBackgroundResource(R.drawable.affiche_user_on);
		} else {
			rightButton.setBackgroundResource(R.drawable.affiche_user_off);
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 接收来自图片下载器的消息
			if (msg.what == 1000) {
				ga.notifyDataSetChanged();
			} else if (msg.what == 1001) {
				// 更新pageControl
				isManualRotated = true;
				pageControl.generatePageControl(msg.arg1);
			} else if (msg.what == 1002) {
				if (msg.arg1 == 0) {
					gallery.setSelection(msg.arg1, true);
				} else {
					// 更新gallery显示
					synchronized (autoRotatedLock) {
						isAutoRatated = true;
						Rect rect = new Rect();
						gallery.getHitRect(rect);
						int x = rect.centerX()
								+ ((Activity) context).getWindowManager()
										.getDefaultDisplay().getWidth();
						int y = rect.centerY();
						MotionEvent event = MotionEvent.obtain(100, 100,
								MotionEvent.ACTION_DOWN, x, y, 0);
						gallery.onDown(event);
						gallery.onSingleTapUp(null);
					}
				}

			}
		}
	};

	class GalleryAdapter extends BaseAdapter {
		ArrayList<GoodsInfo> goodsInfo;
		Context context;
		DisplayMetrics dm;

		public GalleryAdapter(Context context) {
			this.context = context;
			// DisplayMetrics用于获取屏幕的尺寸信息
			dm = new DisplayMetrics();
			((Activity) getContext()).getWindowManager().getDefaultDisplay()
					.getMetrics(dm);
		}

		@Override
		public int getCount() {
			return newGoodsInfo.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			int screenHeight = dm.heightPixels;
			int height = (int) (screenHeight * 0.6);
			int width = (height * 3 / 4);
			if (bitmaps.size() > position) {
				RelativeLayout view = new RelativeLayout(context);
				view.setLayoutParams(new Gallery.LayoutParams(width, height));
				view.setPadding(1, 1, 1, 1);
				view.setBackgroundColor(R.color.Gray);
				ImageView img = new ImageView(context);
				LayoutParams imgparams = generateDefaultLayoutParams();
				imgparams.height = LayoutParams.FILL_PARENT;
				imgparams.width = LayoutParams.FILL_PARENT;
				img.setLayoutParams(imgparams);
				img.setImageBitmap(bitmaps.get(position));
				img.setScaleType(ImageView.ScaleType.FIT_XY);
				view.addView(img);
				TextView text = new TextView(context);
				RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
						ViewGroup.LayoutParams.FILL_PARENT,
						ViewGroup.LayoutParams.WRAP_CONTENT);
				lp1.addRule(RelativeLayout.CENTER_HORIZONTAL);
				lp1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
				String goodsName = getGoodsNameFixedLength(newGoodsInfo.get(
						position).getGoodsName());
				text.setText(goodsName);
				text.setSingleLine();
				text.setGravity(Gravity.CENTER);
				text.setBackgroundResource(R.drawable.details_segment_2_on);
				view.addView(text, lp1);
				return view;
			} else {
				RelativeLayout layout = new RelativeLayout(context);
				layout.setLayoutParams(new Gallery.LayoutParams(width, height));
				layout.setBackgroundColor(R.color.Gray);
				RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
						ViewGroup.LayoutParams.WRAP_CONTENT,
						ViewGroup.LayoutParams.WRAP_CONTENT);
				lp1.addRule(RelativeLayout.CENTER_IN_PARENT);
				ProgressBar bar = new ProgressBar(context);
				layout.addView(bar, lp1);
				return layout;
			}

		}

		private String getGoodsNameFixedLength(String goodsName) {
			if (goodsName.length() <= 32) {
				return goodsName;
			} else {
				return goodsName.substring(0, 31) + "...";
			}
		}
	}

	/**
	 * 异步下载图片线程
	 */
	class LoadImgThread extends Thread {
		List<String> networkImgSrc;

		public LoadImgThread(List<String> imgUrls) {
			networkImgSrc = imgUrls;
		}

		@Override
		public void run() {
			bitmaps = new ArrayList<Bitmap>();
			for (int i = 0; i < networkImgSrc.size(); i++) {
				String url = networkImgSrc.get(i);
				try {
					Bitmap img = Constants.drawableToBitmap(AsyncImageLoader
							.loadImageFromUrl(url));
					Message msg = new Message();
					msg.what = 1000;
					bitmaps.add(img);
					handler.sendMessage(msg);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	class GoodsListAsync extends AsyncTask<Void, Integer, ArrayList<GoodsInfo>> {
		public GoodsListAsync(Context context) {
		}

		@Override
		protected void onPreExecute() {
			loadingLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected ArrayList<GoodsInfo> doInBackground(Void... params) {
			newGoodsInfo = WebServiceClient.getNew(10);
			// add by dave 获得系统图片前缀，系统参数
			WebServiceClient.getImagePreUrl();
			WebServiceClient.getSystemParams();
			return newGoodsInfo;
		}

		@Override
		protected void onPostExecute(ArrayList<GoodsInfo> result) {
			loadFinished = true;
			loadingLayout.setVisibility(View.GONE);
			pageControl.setVisibility(View.VISIBLE);
			logo.setVisibility(View.VISIBLE);
			List<String> imgUrls = new ArrayList<String>();
			for (GoodsInfo goodsInfo : result) {
				imgUrls.add(goodsInfo.getGoodsThumb());
			}
			LoadImgThread thread = new LoadImgThread(imgUrls);
			thread.start();
			ga.notifyDataSetChanged();
			pageControl.setCount(result.size());
			pageControl.generatePageControl(0);
			pageControl.postInvalidate();

			rotateTimer = new Timer();
			rotateTimer.schedule(new RotateTask(), 6000, 3000);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.leftBtn:
			viewFlipper.showPrevious();
			viewFlipper.removeView(this);
			break;
		case R.id.rightBtn:
			if (Constants.userInfo == null) {
				UserLoginLayout userLoginLayout = new UserLoginLayout(context,
						viewFlipper);
				viewFlipper.addView(userLoginLayout);
				viewFlipper.showNext();
			} else {
				Intent myIntent = new Intent();// 创建Intent对象
				myIntent.setAction("com.wholesale.utils.UpdateUIService");
				myIntent.putExtra("cmd", Constants.CMD_MYACCOUNT_SERVICE);
				myIntent.putExtra("from", "com.wholesale.WholeSaleLayout");
				((Activity) getContext()).sendBroadcast(myIntent);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		synchronized (autoRotatedLock) {
			if (loadFinished) {
				if (!isAutoRatated) {
					if (arg2 < newGoodsInfo.size()) {
						GoodsDetailLayout goodsDetailLayout = new GoodsDetailLayout(
								WholeSaleLayout.this.context, viewFlipper,
								"Back", newGoodsInfo.get(arg2));
						viewFlipper.addView(goodsDetailLayout);
						viewFlipper.showNext();
					}
				} else {
					isAutoRatated = false;
				}
			}
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		Message msg = new Message();
		msg.what = 1001;
		msg.arg1 = arg2;
		handler.sendMessage(msg);
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}
}
